package com.baiyang.server.task;

import com.baiyang.server.model.base.ItemU;
import com.baiyang.server.model.read.ReadRecord;
import com.baiyang.server.service.base.ItemUService;
import com.baiyang.server.service.read.ReadRecordService;
import com.baiyang.server.service.system.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class TimeTask {
    @Autowired
    private UserService userService = null;
    @Autowired
    private ReadRecordService readRecordService = null;
    @Autowired
    private ItemUService itemUService = null;

    /**
     * 通过欧几里得公式计算用户之间的相似度
     */
//    @Scheduled(cron = "0 0 1 * * ?")  // 每天一点执行
    @Scheduled(cron = "0/10 * * * * ?")  // 每过10秒执行此方法
    public void getSimilarity(){
        List<ItemU> itemUList = itemUService.selectList(new ItemU());
        itemUList.forEach(itemU -> {
            itemU.setSimilarity(getItemSimilarity(itemU));
            itemUService.updateById(itemU);
        });
    }

    private Double getItemSimilarity(ItemU itemU){
        // 获取两个用户的阅读记录
        List<ReadRecord> x = readRecordService.selectByUserId(itemU.getUserId());
        List<ReadRecord> y = readRecordService.selectByUserId(itemU.getRelationId());
        List<String> articles = new ArrayList<>();
        x.forEach(e->{
            articles.add(e.getArticleId());
        });
        y.forEach(e->{
            articles.add(e.getArticleId());
        });
        Double sim = 0d;
        for (String e :articles){
            ReadRecord xRecord = null, yRecord = null;
            for (ReadRecord readRecord : x) {
                if(readRecord.getArticleId().equals(e)){
                    xRecord = readRecord;
                    break;
                }
            }
            for (ReadRecord readRecord : y) {
                if(readRecord.getArticleId().equals(e)){
                    yRecord = readRecord;
                    break;
                }
            }
            if(xRecord == null || yRecord == null){
                continue;
            }
            sim += Math.pow((xRecord.getScore()==null?25:xRecord.getScore()) - (yRecord.getScore()==null?25:yRecord.getScore()),2);
        }
        if(sim == 0){
            return 1d;
        }
        String str = String.format("%.3f", 1/Math.sqrt(sim)); //以字符串形式保留位数，此处保留3位小数
        double similarity = Double.parseDouble(str); //将字符串转回double类型
        return similarity;
    }

}
